
package upc.pilot.Servlet;

import java.awt.image.BufferedImage;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Date;
import java.util.Enumeration;
import java.util.Properties;

import javax.imageio.ImageIO;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.google.code.kaptcha.Constants;
import com.google.code.kaptcha.Producer;
import com.google.code.kaptcha.util.Config;

/**
 * Servlet implementation class KaptchaServlet
 */
@WebServlet("/KaptchaServlet")
public class KaptchaServlet extends HttpServlet
{
    private static final long serialVersionUID = 1L;
    private Properties props = new Properties();
    private Producer kaptchaProducer = null;
    private String sessionKeyValue = null;
    private String sessionKeyDateValue = null;

    /**
     * @see HttpServlet#HttpServlet()
     */
    public KaptchaServlet()
    {
        super();
        // TODO Auto-generated constructor stub
    }

    public void init(ServletConfig config) throws ServletException
    {
        // TODO Auto-generated method stub
        super.init(config);
        ImageIO.setUseCache(false);
        Enumeration<?> initParams = config.getInitParameterNames();
        while (initParams.hasMoreElements())
        {
            String key = (String) initParams.nextElement();
            String value = config.getInitParameter(key);
            this.props.put(key, value);
        }
        Config configuration = new Config(this.props);
        this.kaptchaProducer = configuration.getProducerImpl();
        this.sessionKeyValue = configuration.getSessionKey();
        this.sessionKeyDateValue = configuration.getSessionDate();
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
    {
        response.setDateHeader("Expires", 0);
        response.setHeader("Cache-Control", "no-store, no-cache, must-revalidate");
        response.addHeader("Cache-Control", "post-check=0, pre-check=0");
        response.setHeader("Pragma", "no-cache");
        response.setContentType("image/jpeg");
        String capText = this.kaptchaProducer.createText();
        request.getSession().setAttribute(this.sessionKeyValue, capText);
        request.getSession().setAttribute(this.sessionKeyDateValue, new Date());
        BufferedImage bi = this.kaptchaProducer.createImage(capText);
        ServletOutputStream out = response.getOutputStream();
        ImageIO.write(bi, "jpg", out);
    }

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException,
            IOException
    {
        String captchaId = (String) request.getSession().getAttribute(Constants.KAPTCHA_SESSION_KEY);
        String parm = (String) request.getParameter("txtResponse");
        if (captchaId != null && parm != null)
        {
            if (captchaId.equals(parm))
            {
                response.setContentType("text/html");
                PrintWriter out = response.getWriter();
                out.write("document.getElementById('imagen_captcha').src='KaptchaServlet#"
                        + Math.floor(Math.random() * 1100000) + "';");
                out.write("document.getElementById('captcha_response').value='';");
                out.write("f_grabarDatos();");
                out.flush();
                out.close();
            }
            else
            {
                response.setContentType("text/html");
                PrintWriter out = response.getWriter();
                out.write("document.getElementById('imagen_captcha').src='KaptchaServlet#"
                        + Math.floor(Math.random() * 1100000) + "';");
                out.write("alert('Codigo incorrecto,registra nuevamente el codigo de la imagen');");
                out.write("document.getElementById('captcha_response').value='';");
                out.write("document.getElementById('captcha_response').focus();");
                out.write("return false;");
                out.flush();
                out.close();
            }
        }
    }

}
